package com.example.data.factory.common.configer;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket ( DocumentationType.SWAGGER_2 )
                .apiInfo ( apiInfo () )
                .select ()
                .apis ( RequestHandlerSelectors.basePackage ( "com.example" ) )
                .paths ( PathSelectors.any () )
                .build ()
                // 配置全局安全上下文
                .securitySchemes ( Collections.singletonList ( securityScheme () ) )
                .securityContexts ( Collections.singletonList ( securityContext () ) );
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder ()
                .title ( "数据工厂接口文档" )
                .description ( "数据工厂接口文档" )
                .version ( "1.0" )
                .termsOfServiceUrl ( "urn:tos" )
                .license ( "Apache 2.0" )
                .licenseUrl ( "https://www.apache.org/licenses/LICENSE-2.0" )
                .build ();
    }

    /**
     * 定义安全方案（Bearer Token）
     */
    private SecurityScheme securityScheme() {
        return new ApiKey ( "Authorization", "Authorization", "header" );
    }

    /**
     * 定义安全上下文
     */
    private SecurityContext securityContext() {
        return SecurityContext.builder ()
                .securityReferences ( defaultAuth () )
                .forPaths ( PathSelectors.any () )
                .build ();
    }

    /**
     * 默认的安全引用
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope ( "global", "accessEverything" );
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
        return Collections.singletonList ( new SecurityReference ( "Authorization", authorizationScopes ) );
    }
}